package itbour.onetouchshow.fragment.movie;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.ys.uilibrary.utils.DisplayUtils;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import itbour.onetouchshow.R;
import itbour.onetouchshow.adapter.FilterAdapter;
import itbour.onetouchshow.adapter.base.BaseAdapterHelper;
import itbour.onetouchshow.adapter.base.recycler.RecyclerAdapter;
import itbour.onetouchshow.base.mvp.MVPBaseFragment;
import itbour.onetouchshow.bean.DesignListBean;
import itbour.onetouchshow.bean.HomeDetailslBean;
import itbour.onetouchshow.bean.VideoConditionBean;
import itbour.onetouchshow.constants.AppConst;
import itbour.onetouchshow.utils.ImageLoader;
import itbour.onetouchshow.utils.JumpUtils;
import itbour.onetouchshow.utils.SpUtils;
import itbour.onetouchshow.utils.UIUtils;
import itbour.onetouchshow.utils.recycleviewmanager.FastScrollManger;
import itbour.onetouchshow.widget.ScaleImageView;

/**
 * Created by guoh on 2018/8/2.
 * 功能描述：玩大片中的一个模板类型
 * 需要的参数：
 */
public class MoviePartFragment extends MVPBaseFragment<ModulePartView, ModulePartPresenter> implements ModulePartView {

    private final int FAST_CLICK_DELAY_TIME = 2000;
    @BindView(R.id.tv_filter_name2)
    TextView tvFilterName2;
    @BindView(R.id.ry_module)
    RecyclerView ryModule;
    @BindView(R.id.ll_filter2)
    LinearLayout llFilter2;
    @BindView(R.id.tv_filter_name1)
    TextView tvFilterName1;
    @BindView(R.id.ry_time)
    RecyclerView ryTime;
    @BindView(R.id.ll_filter1)
    LinearLayout llFilter1;
    @BindView(R.id.ll_filter_layout)
    LinearLayout llFilterLayout;
    @BindView(R.id.tv_filter_rule)
    TextView tvFilterRule;
    @BindView(R.id.iv_filter_rule)
    ImageView ivFilterRule;
    @BindView(R.id.ll_filter_rule)
    LinearLayout llFilterRule;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.id_back_top)
    ImageView idBackTop;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.ll_no_network)
    LinearLayout llNoNetwork;
    private FilterAdapter filterAdapter1;
    private FilterAdapter filterAdapter2;
    //动画时间
    private int animationTime = 200;
    //两筛选条件
    private VideoConditionBean.Option filterRuleOption1;
    private VideoConditionBean.Option filterRuleOption2;
    //两筛选条件
    private VideoConditionBean.Option allRuleOption1;
    private VideoConditionBean.Option allRuleOption2;
    //是否执行了动画
    private boolean executeTheAnimation = false;
    private VideoConditionBean conditionBean;
    private long lastClickTime = 0L;
    private List<Integer> ids;

    private ModuleAdapter adapter;

    private DesignListBean designListBean;

    private FastScrollManger layoutManager;


    @Override
    protected int getLayoutId() {
        return R.layout.fr_module_part;
    }

    @Override
    protected void afterCreate(Bundle bundle) {
        initFilter();
        initRecycleView();
        Bundle dataBundle = getArguments();
        ids = dataBundle.getIntegerArrayList(AppConst.KEY_MODULE_IDS);
        requestData(true);
    }

    @OnClick(R.id.ll_filter_rule)
    public void onViewClicked() {
        setFilterTextAlphaAnimation(1, 0, animationTime);
    }


    @Override
    public void obtainListSuccess(String response, boolean reload) {
        designListBean = new Gson().fromJson(response, DesignListBean.class);
        List<DesignListBean.ListBean> resultData = designListBean.getList();
        if (resultData == null || resultData.size() <= 0) {
            //没有更多数据
            if (!reload) {
                //显示没有更多数据
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishRefresh(true);
                if (llNoNetwork.getVisibility() == View.VISIBLE) {
                    llNoNetwork.setVisibility(View.GONE);
                }
                llNoData.setVisibility(View.VISIBLE);
                refreshLayout.setEnableLoadMore(false);
            }
            return;
        } else {
            //有数据
            if (llNoData.getVisibility() == View.VISIBLE) {
                llNoData.setVisibility(View.GONE);
                refreshLayout.setEnableLoadMore(true);
            }
            if (llNoNetwork.getVisibility() == View.VISIBLE) {
                llNoNetwork.setVisibility(View.GONE);
                refreshLayout.setEnableLoadMore(true);
            }
            if (reload) {
                refreshLayout.finishRefresh(true);
                refreshLayout.setNoMoreData(false);
            } else {
                refreshLayout.finishLoadMore(true);
            }
        }
        resultData = calculateImageHeightAndWidth(resultData);
        if (reload) {
            adapter.replaceAll(resultData);
        } else adapter.addAll(resultData);
    }


    private List<DesignListBean.ListBean> calculateImageHeightAndWidth(List<DesignListBean.ListBean> datas) {
        for (DesignListBean.ListBean data : datas) {
            int width = UIUtils.WHD()[0] / 2 - UIUtils.dp2px(6);
            int height = width * data.getH() / data.getW();
            String imUrl;
            if (data.getThumb() != null) {
                imUrl = ImageLoader.getShrinkImageUrl(data.getThumb(), width, height);
                data.setThumb(imUrl);
            }
            data.setW(width);
            data.setH(height);
        }
        return datas;
    }

    private void requestData(boolean reload) {
        mPresenter.getModuleDetails(ids, getDurationKey(), getDurationValue(), getTmplTypeKey(), getTmplTypeValue(), reload);
    }

    private void initRecycleView() {
        refreshLayout.setEnableRefresh(true);
        refreshLayout.setEnableLoadMore(true);
        //不满一页 不允许上拉加载更多
        refreshLayout.setEnableLoadMoreWhenContentNotFull(false);
        refreshLayout.setEnableAutoLoadMore(true);
        refreshLayout.setEnableFooterFollowWhenLoadFinished(true);
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                requestData(false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                requestData(true);
            }
        });
        adapter = new ModuleAdapter(getContext());
        recyclerView.setHasFixedSize(true);
        layoutManager = new FastScrollManger(2, StaggeredGridLayoutManager.VERTICAL);
        layoutManager.setGapStrategy(StaggeredGridLayoutManager.GAP_HANDLING_NONE);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        adapter.setOnItemClickListener(new onItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
                    return;
                }
                lastClickTime = System.currentTimeMillis();
                JumpUtils.goToVideoPlayer(getActivity(), adapter.getData().get(position).getId());
            }
        });

        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int lastBottomCompletelyEmergedItemPosition =
                            layoutManager.findLastBottomCompletelyEmergedItemPosition();
                    if (lastBottomCompletelyEmergedItemPosition > 0) {
                        if (idBackTop != null) {
                            idBackTop.setVisibility(View.VISIBLE);
                        }

                    } else {
                        if (idBackTop != null) {
                            idBackTop.setVisibility(View.INVISIBLE);
                        }

                    }
                }
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    if (llFilterLayout.getVisibility() == View.GONE) return;
                    if (!executeTheAnimation && adapter.getData().size() > 4) {
                        executeTheAnimation = true;
                        setFilterLayoutAlphaAnimation(1, 0, animationTime);
                    }
                }

            }
        });


        idBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layoutManager.scrollToPositionWithOffset(0, 0);
                idBackTop.setVisibility(View.INVISIBLE);
            }
        });
    }

    private void initFilter() {
        filterAdapter1 = new FilterAdapter(getContext());
        filterAdapter2 = new FilterAdapter(getContext());
        ryTime.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        ryModule.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false));
        ryTime.setAdapter(filterAdapter1);
        ryTime.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        ryModule.setAdapter(filterAdapter2);

        conditionBean = new Gson().fromJson(SpUtils.getInstance().getString(AppConst.APPBASEINFO), HomeDetailslBean.class).getVideoConditions();
        //以下皆为动态判断后台数据有空值 界面应正常显示
        if (conditionBean.getDurationCondition() != null) {
            if (conditionBean.getDurationCondition().getOptions() != null && conditionBean.getDurationCondition().getOptions().size() > 0 && conditionBean.getDurationCondition().getOptions().get(0) != null) {
                conditionBean.getDurationCondition().getOptions().get(0).setSelected(true);
                allRuleOption1 = conditionBean.getDurationCondition().getOptions().get(0);
            }
            setFilter1(conditionBean);
        } else {
            llFilter1.setVisibility(View.GONE);
        }
        if (conditionBean.getIndustryCondition() != null) {
            if (conditionBean.getIndustryCondition().getOptions() != null && conditionBean.getIndustryCondition().getOptions().size() > 0 && conditionBean.getIndustryCondition().getOptions().get(0) != null) {
                conditionBean.getIndustryCondition().getOptions().get(0).setSelected(true);
                allRuleOption2 = conditionBean.getIndustryCondition().getOptions().get(0);
            }
            setFilter2(conditionBean);
        } else {
            llFilter2.setVisibility(View.GONE);
        }

        llFilterLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                llFilterLayout.requestDisallowInterceptTouchEvent(true);
                return true;
            }
        });
        ryModule.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ryModule.requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });
        ryTime.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                ryTime.requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });

    }

    //Alpha动画
    private void setFilterLayoutAlphaAnimation(float form, float to, int time) {
        ValueAnimator va = ValueAnimator.ofFloat(form, to);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                if (llFilterLayout.getVisibility() == View.GONE) {
                    llFilterLayout.setVisibility(View.VISIBLE);
                }
                float h = (Float) valueAnimator.getAnimatedValue();
                llFilterLayout.setAlpha(h);
            }


        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (form == 1) {
                    llFilterLayout.setVisibility(View.GONE);
                    llFilterLayout.setAlpha(1);
                    executeTheAnimation = false;
                    setFilterTextAlphaAnimation(0, 1, animationTime);
                    // setFilterLayoutHeightAnimation(DisplayUtils.dip2px(getContext(),90),DisplayUtils.dip2px(getContext(),40),animationTime);
                } else {
                    executeTheAnimation = false;
                }
            }
        });
        va.setDuration(time);
        va.start();
    }

    private void setFilterTextAlphaAnimation(float form, float to, int time) {
        ValueAnimator va = ValueAnimator.ofFloat(form, to);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                float h = (Float) valueAnimator.getAnimatedValue();
                if (llFilterRule.getVisibility() == View.GONE) {
                    llFilterRule.setVisibility(View.VISIBLE);
                }
                llFilterRule.setAlpha(h);
            }


        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                if (form == 1) {
                    //消失
                    llFilterRule.setVisibility(View.GONE);
                    llFilterRule.setAlpha(1);
                    setFilterLayoutAlphaAnimation(0, 1, animationTime);
                }
            }
        });
        va.setDuration(time);
        va.start();
    }

    //两行筛选缩起 弹出筛选条件 高度动画
    private void setFilterLayoutHeightAnimation(int form, int to, int time) {
        ValueAnimator va = ValueAnimator.ofInt(form, to);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int h = (Integer) valueAnimator.getAnimatedValue();
                llFilterLayout.getLayoutParams().height = h;
                llFilterLayout.requestLayout();
            }

        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                //偏移量5dp
                if (llFilterLayout.getHeight() < DisplayUtils.dip2px(getActivity(), 5)) {
                    setFilterTextHeightAnimation(0, DisplayUtils.dip2px(getActivity(), 45), animationTime);
                } else {
                    executeTheAnimation = false;
                }
            }
        });
        va.setDuration(time);
        va.start();
    }

    //缩起筛选条件 弹出两行筛选
    private void setFilterTextHeightAnimation(int form, int to, int time) {
        ValueAnimator va = ValueAnimator.ofInt(form, to);
        va.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator valueAnimator) {
                int h = (Integer) valueAnimator.getAnimatedValue();
                llFilterRule.getLayoutParams().height = h;
                llFilterRule.requestLayout();
            }

        });
        va.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                //偏移量5dp
                if (llFilterRule.getHeight() < DisplayUtils.dip2px(getActivity(), 5)) {
                    setFilterLayoutHeightAnimation(0, DisplayUtils.dip2px(getContext(), 90), animationTime);
                }
            }
        });

        va.setDuration(time);
        va.start();
    }

    //设置筛选1的选中
    private void setFilter1(VideoConditionBean videoConditionBean) {
        tvFilterName1.setText(videoConditionBean.getDurationCondition().getName());
        filterAdapter1.replaceAll(videoConditionBean.getDurationCondition().getOptions());
        filterAdapter1.setonItemClickListener(new FilterAdapter.onItemClickListener() {
            @Override
            public void onItemClickListener(int position, VideoConditionBean.Option option) {
                for (VideoConditionBean.Option o : filterAdapter1.getData()) {
                    o.setSelected(false);
                }
                filterAdapter1.getItem(position).setSelected(true);
                filterAdapter1.notifyDataSetChanged();
                filterRuleOption1 = option;
                if (position == 0) filterRuleOption1 = null;
                setRuleText();
                scrollToMiddle(ryTime, position);
            }
        });
    }

    private void scrollToMiddle(RecyclerView recyclerview, int position) {
        int firstPosition = ((LinearLayoutManager) recyclerview.getLayoutManager()).findFirstVisibleItemPosition();
        int lastPosition = ((LinearLayoutManager) recyclerview.getLayoutManager()).findLastVisibleItemPosition();
        int left = recyclerview.getChildAt(position - firstPosition).getLeft();
        int right = recyclerview.getChildAt(lastPosition - position).getLeft();
        recyclerview.scrollBy((left - right) / 2, 0);
    }

    //设置筛选2的选中
    private void setFilter2(VideoConditionBean videoConditionBean) {
        tvFilterName2.setText(videoConditionBean.getIndustryCondition().getName());
        filterAdapter2.replaceAll(videoConditionBean.getIndustryCondition().getOptions());
        filterAdapter2.setonItemClickListener(new FilterAdapter.onItemClickListener() {
            @Override
            public void onItemClickListener(int position, VideoConditionBean.Option option) {
                for (VideoConditionBean.Option o : filterAdapter2.getData()) {
                    o.setSelected(false);
                }
                filterAdapter2.getItem(position).setSelected(true);
                filterAdapter2.notifyDataSetChanged();
                filterRuleOption2 = option;
                if (position == 0) filterRuleOption2 = null;
                setRuleText();
                scrollToMiddle(ryModule, position);
            }
        });
    }

    //设置筛选条件内容
    private void setRuleText() {
        if (filterRuleOption1 == null && filterRuleOption2 == null) {
            ivFilterRule.setVisibility(View.VISIBLE);
            tvFilterRule.setText("筛选");
        } else if (filterRuleOption1 == null && filterRuleOption2 != null) {
            ivFilterRule.setVisibility(View.GONE);
            tvFilterRule.setText(filterRuleOption2.getName());
        } else if (filterRuleOption1 != null && filterRuleOption2 == null) {
            ivFilterRule.setVisibility(View.GONE);
            tvFilterRule.setText(filterRuleOption1.getName());
        } else {
            ivFilterRule.setVisibility(View.GONE);
            tvFilterRule.setText(filterRuleOption2.getName() + " • " + filterRuleOption1.getName());
        }

        requestData(true);
    }

    //组装key
    private String getDurationKey() {
        if (conditionBean == null) return null;
        else if (conditionBean != null) {
            if (conditionBean.getDurationCondition() == null)
                return null;
            else return conditionBean.getDurationCondition().getRequestKey();
        }
        return null;
    }

    //组装value
    private String getDurationValue() {
        if (filterRuleOption1 == null)
            return (allRuleOption1 == null ? "" : new Gson().toJson(allRuleOption1.getValues()));
        else return new Gson().toJson(filterRuleOption1.getValues());
    }

    //组装key
    private String getTmplTypeKey() {
        if (conditionBean == null) return null;
        else if (conditionBean != null) {
            if (conditionBean.getIndustryCondition() == null)
                return null;
            else return conditionBean.getIndustryCondition().getRequestKey();
        }
        return null;
    }

    //组装value
    private String getTmplTypeValue() {
        if (filterRuleOption2 == null)
            return (allRuleOption2 == null ? "" : new Gson().toJson(allRuleOption2.getValues()));
        else return new Gson().toJson(filterRuleOption2.getValues());
    }

    @Override
    public void loadSucceed(String result) {
    }

    @Override
    public void loadFaild(String error) {
        refreshLayout.finishRefresh(false);
        refreshLayout.finishLoadMore(false);
        if (llNoData.getVisibility() == View.VISIBLE) {
            llNoData.setVisibility(View.GONE);
        }
        llNoNetwork.setVisibility(View.VISIBLE);
        refreshLayout.setEnableLoadMore(false);
    }

    public interface onItemClickListener {
        void onItemClick(int position);
    }

    public class ModuleAdapter extends RecyclerAdapter<DesignListBean.ListBean> {

        private onItemClickListener onItemClickListener;

        public ModuleAdapter(Context context) {
            super(context, R.layout.itme_main_frag_v3);
        }

        public void setOnItemClickListener(MoviePartFragment.onItemClickListener onItemClickListener) {
            this.onItemClickListener = onItemClickListener;
        }

        @Override
        protected void convert(BaseAdapterHelper helper, DesignListBean.ListBean item, int position) {
            ScaleImageView imageView = helper.getView(R.id.id_ig);
            TextView tvName = helper.getView(R.id.id_tv_name);
            TextView tvCount = helper.getView(R.id.id_tv_count);
            ImageView vip = helper.getView(R.id.iv_vip_template);
            vip.setVisibility(item.isVipTemplate() ? View.VISIBLE : View.GONE);
            imageView.setInitSize(item.getW(), item.getH());
            ImageLoader.getInstance().showCircleImageWithBorder(getContext(), item.getThumb(), imageView);
            tvName.setText(item.getName());
            tvCount.setText(item.getUseCounts() + "人使用");

            helper.setTag(R.id.ll_layout, position).setOnClickListener(R.id.ll_layout, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (onItemClickListener != null) {
                        onItemClickListener.onItemClick(Integer.parseInt(v.getTag().toString()));
                    }
                }
            });
        }

    }
}
